﻿// =================================================================== 
// 项目说明
//====================================================================
// 
// 文件： SYS_DEPT.cs
// 项目名称：


// 创建时间：2013/3/19
// 负责人：
// ===================================================================
using System;
using System.Data;
using CommonLib.Model;
using CommonLib.IDAL;
using CommonLib.DALFactory;

namespace CommonLib.BLL
{
    /// <summary>
    ///   的BLL层


    /// </summary>
    public class SYS_DEPT : SYS_DEPTBLLBase
    {
		#region ----------变量定义----------
		#endregion
		
		#region ----------构造函数----------
		/// <summary>
		/// 默认构造函数


		/// </summary>
		public SYS_DEPT()
		{
		}
		#endregion
		
		#region----------函数定义---------
		public static DataSet GetListSub(string sWhere, string sOder)
        {
            // Use the dal to get all records 
            return _dal.GetListSub(sWhere, sOder);
        }

        public static string GetNewDeptId(string parentId)
        {
            /**
             * 按顺序产生1-99
             * 如果超过99就返回从1-99找未使用过的最小值
             * 1-99 都满了则返回错误
             */

            parentId = parentId.Trim();
            string DEPT_ID = "";
            string sql = string.Format("SELECT RTRIM(LTRIM(DEPT_ID)) DEPT_ID,Substring(RTRIM(LTRIM(DEPT_ID)),{0},20) NID FROM SYS_DEPT where RTRIM(LTRIM(PARENT_ID))='{1}' ORDER BY RTRIM(LTRIM(DEPT_ID)) asc", parentId.Length + 1, parentId);

            DataTable idsdt = CommonLib.BLL.BS_DATASET_SQL.SqlGetTable(sql);
            if (idsdt.Rows.Count >= 99)
            {
                throw new Exception("子部门超过99个!");
            }
            else
            {
                int newid = 1;
                if (idsdt.Rows.Count > 0)
                {
                    newid = Convert.ToInt32(idsdt.Rows[idsdt.Rows.Count - 1]["NID"]);
                    if (newid >= 99)
                    {
                        int t = 0;
                        for (int i = 0; i < idsdt.Rows.Count; i++)
                        {
                            int next = Convert.ToInt32(idsdt.Rows[i]["NID"]);
                            if (t + 1 != next)
                            {
                                newid = t + 1;
                                break;
                            }
                            t = next;
                        }
                    }
                    else
                    {
                        newid = newid + 1;
                    }
                }
                DEPT_ID = parentId + newid.ToString("00");
            }
            return DEPT_ID;
        }
		#endregion
	}

}
